package com.yiwei.hdb.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.widget.ImageView;

import com.yiwei.hdb.R;

/**
 * Created by xsooy-pc on 2017/5/10.
 */

public class AutoSetHeightImageView extends ImageView {
    private float height;
    private float width;

    public AutoSetHeightImageView(Context context) {
        super(context, null);
        init(context, null);
    }

    public AutoSetHeightImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs, 0);
        init(context, attrs);
    }

    public AutoSetHeightImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.AutoSetHeightImageView);
        height = a.getFloat(R.styleable.AutoSetHeightImageView_autoSetHeight, 0f);
        width = a.getFloat(R.styleable.AutoSetHeightImageView_autoSetWidth, 0f);
        a.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int specMode = MeasureSpec.getMode(widthMeasureSpec);
        int specSize = MeasureSpec.getSize(widthMeasureSpec);
        int result = 500;
        if (specMode == MeasureSpec.AT_MOST) {//相当于我们设置为wrap_content
            result = specSize;
        } else if (specMode == MeasureSpec.EXACTLY) {//相当于我们设置为match_parent或者为一个具体的值
            result = specSize;
        }
        int height = (int) (result * this.height / this.width);
        setMeasuredDimension(result, height);
    }
}
